<template>

  <el-select
    v-model="selectValue"
    filterable
    :clearable="false"
    @change="afterChange"
    :placeholder="$tt('tip_please_select')"
    multiple
  >
    <el-option v-for="item in options" :key="item.id" :label="'[' + item.code + '] ' + item.name" :value="item.id">
    </el-option>
  </el-select>

</template>


<script>

  import Vue from 'vue'

  import {mapState} from "vuex";

  export default {
    name: 'warehouse_select',
    data() {
      return {

        hasLoad: false,
        selectValue: [],
        options: [],
        optionMap: {}

      }
    },

    watch: {

      value: function (val, old) {

        if (val) {
          this.selectValue = val.map(ee => ee.warehouseId + '')

        } else {
          this.selectValue = []
        }
      }
    },

    props: {

      value: null,

    },

    created() {

      let _this = this

      if (this.value) {
        this.selectValue = this.value.map(ee => ee.warehouseId + '')
      }

      if(Vue.prototype.$pmsWarehouseHasLoad){
        _this.options = Vue.prototype.$pmsWarehouseOptionCache
        _this.options.forEach(rr => {
          rr.id = rr.id + ''
          _this.optionMap[rr.id] = rr
        })
        return
      }

      _this.$ajax({
        url: '/oms-api/base/OmsBaseWarehouseRpc/selectAllEnable.json',
        success: function (res) {

          _this.options = res.data.rows

          _this.options.forEach(rr => {
            rr.id = rr.id + ''
            _this.optionMap[rr.id] = rr
          })

          Vue.prototype.$pmsWarehouseHasLoad = true
          Vue.prototype.$pmsWarehouseOptionCache = res.data.rows
        }
      })


    },

    methods: {

      afterChange(val) {

        let result = val.map(e => {

          return {
            "warehouseId": this.optionMap[e].id,
            "warehouseName": this.optionMap[e].name,
            "warehouseCode": this.optionMap[e].code
          }
        })
        this.$emit('input', result)
      }

    }
  }
</script>
